<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="轮播图状态" clearable>
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="plus"
            @click="handleAdd"
            v-hasPermi="['carousel:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['carousel:banner:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" row-key="bannerId" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图片" width="150" align="center">
        <template #default="{ row }">
          <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 100px; height: 50px; cursor: pointer"
          />
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="跳转链接" prop="targetUrl" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="排序" prop="sort" align="center">
        <template #default="{ row }">
          <el-input-number
              v-model="row.sort"
              :min="0"
              size="small"
              @change="handleSortChange(row)"
              :disabled="!hasPermi(['carousel:banner:edit'])"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <el-switch
              v-model="row.status"
              :active-value="'0'"
              :inactive-value="'1'"
              @change="handleStatusChange(row)"
              :disabled="!hasPermi(['carousel:banner:edit'])"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="{ row }">
          {{ parseTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleUpdate(row)" v-hasPermi="['carousel:banner:edit']">编辑</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)" v-hasPermi="['carousel:banner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px" @close="cancel" append-to-body>
      <el-form ref="bannerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <ImageUpload v-model="form.imageUrl" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="targetUrl">
          <el-input v-model="form.targetUrl" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls controls-position="right"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listBanner, getBanner, addBanner, updateBanner, delBanner, changeBannerStatus } from "@/api/carousel/banner";
import ImageUpload from "@/components/ImageUpload";
import { parseTime } from "@/utils/ruoyi";
import { ElMessage, ElMessageBox } from 'element-plus';
import auth from '@/plugins/auth';

const { proxy } = getCurrentInstance();

const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const bannerList = ref([]);
const open = ref(false);
const title = ref("");
const multiple = ref(true);
const ids = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  status: undefined
});

const form = reactive({
  bannerId: null,
  title: "",
  imageUrl: "",
  targetUrl: "",
  sort: 0,
  status: "0"
});

const rules = {
  imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }]
};

const hasPermi = (permission) => {
  return auth.hasPermi(permission);
};

// 查询列表
const getList = () => {
  loading.value = true;
  listBanner(queryParams).then(response => {
    bannerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

// 多选
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.bannerId);
  multiple.value = !selection.length;
};

// 新增
const handleAdd = () => {
  form.bannerId = null;
  form.title = "";
  form.imageUrl = "";
  form.targetUrl = "";
  form.sort = 0;
  form.status = "0";
  open.value = true;
  title.value = "添加轮播图";
};

// 编辑
const handleUpdate = (row) => {
  getBanner(row.bannerId).then(response => {
    Object.assign(form, response.data);
    open.value = true;
    title.value = "修改轮播图";
  });
};

// 删除
const handleDelete = (row) => {
  const bannerIds = row.bannerId || ids.value;
  ElMessageBox.confirm('是否确认删除选中的轮播图？', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delBanner(bannerIds).then(() => {
      ElMessage.success("删除成功");
      getList();
    });
  });
};

// 状态切换
const handleStatusChange = (row) => {
  const text = row.status === "0" ? "启用" : "禁用";
  ElMessageBox.confirm(`确认要"${text}"该轮播图吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    changeBannerStatus(row).then(() => {
      ElMessage.success(`${text}成功`);
    });
  }).catch(() => {
    row.status = row.status === "0" ? "1" : "0";
  });
};

// 排序变更
const handleSortChange = (row) => {
  updateBanner(row).then(() => {
    ElMessage.success("排序更新成功");
  });
};

// 提交
const submitForm = () => {
  proxy.$refs.bannerRef.validate(valid => {
    if (valid) {
      if (form.bannerId) {
        updateBanner(form).then(() => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBanner(form).then(() => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 取消
const cancel = () => {
  open.value = false;
  proxy.$refs.bannerRef.resetFields();
};

// 初始化
getList();
</script>